import {
	baseUrl
} from '../config'


export function uploadFile(url, path, formData) {
	return new Promise((reslove, reject) => {
		uni.uploadFile({
			url: baseUrl + url,
			filePath: path,
			name: 'file',
			formData: formData,
			header: {
				token: uni.getStorageSync('token'),
			},
			success: res => {
				var data = typeof res.data == 'string' ? JSON.parse(res.data) : res.data; //微信和头条支持
				if (data.code !== 200) {
					uni.showModal({
						showCancel: false,
						content: data.message
					})
				}
				reslove({
					success: data.code === 200,
					...data
				})

			},
			fail(err) {
				reslove({
					success: false,
					message: err
				})
			}
		})
	})
}

export default function request(uri, data = {}, type = 'POST', contentType = 'application/json;charset=UTF-8') {
	let url = baseUrl + uri
	let header = {
		// 'SID':uri,
		'Content-Type': contentType
	}
	header = {
		...header,
		token: uni.getStorageSync('token')
	}
	return new Promise(function(reslove, reject) {
		try {
			uni.request({
				url: url,
				// timeout: 3000,
				header: header,
				method: type,
				data: data,
				success: res => {
					// console.log(res)
					res.data = res.data || {};
					res.data.success = res.data.code == 0
					if (res.data.code == 0){
						// if (uri.indexOf('checkLogin') > -1) {
						// 	let xtoken = res.data.data.userId
						// 	uni.setStorageSync('token', xtoken)
						// }
						reslove(res.data);
					} else {
						if (res.data.code == 401) {
							uni.removeStorageSync('token')
							uni.showModal({
								title: "提示",
								content: '登录超时,请重新登陆',
								confirmText: '去登陆',
								showCancel: false,
								success(res) {
									if (res.confirm) {
										const pages = getCurrentPages();
										uni.navigateTo({
											url: '/pages/login/login?url=' + encodeURIComponent('/' + pages[pages.length - 1].route)
										})
									}
								}
							});
						} else {
							//console.error(res.data.msg)
							// uni.showModal({
							// 	content: res.data.msg,
							// 	showCancel: false
							// });
						}
						reslove(res.data)
					}
				},
				fail: (err) => {
					reslove({
						success: false,
						msg: err.errMsg
					})
				}
			});
		} 
		catch (err) {
			reslove({
				success: false,
				msg: err
			})
		}
	})
}